﻿using System;
using System.Diagnostics.Contracts;
using System.Globalization;
using System.Windows;
using System.Windows.Data;
using System.Windows.Media;

namespace ICodeShare.UI.Converters
{
    /// <summary>
    /// Brush值转换成相近的黑色画刷或白色画刷
    /// </summary>
    [ValueConversion(typeof(SolidColorBrush), typeof(Brush))]
    public class BrushToRoundBrushConverter : IValueConverter
    {
        #region Construction
        /// <summary>
        /// 
        /// </summary>
        public BrushToRoundBrushConverter()
        {

        }

        /// <summary>
        /// 实例化一个BrushToRoundBrushConverter类
        /// </summary>
        /// <param name="lightBrush">浅色</param>
        /// <param name="deepBrush">深色</param>
        public BrushToRoundBrushConverter(Brush lightBrush, Brush deepBrush)
        {
            this.LightBrush = lightBrush;
            this.DeepBrush = deepBrush;
        }
        #endregion

        #region Properties

        private Brush _lightBrush = Brushes.White;
        /// <summary>
        /// 高近似值
        /// </summary>
        public Brush LightBrush
        {
            get { return _lightBrush; }
            set { _lightBrush = value; }
        }

        private Brush _deepBrush = Brushes.Black;
        /// <summary>
        /// 低近似值
        /// </summary>
        public Brush DeepBrush
        {
            get { return _deepBrush; }
            set { _deepBrush = value; }
        }

        #endregion

        public object Convert(object value, Type targetType, object parameter, CultureInfo culture)
        {
            var solidColorBrush = value as SolidColorBrush;
            if (solidColorBrush == null) return null;

            var color = solidColorBrush.Color;

            var brightness = 0.3 * color.R + 0.59 * color.G + 0.11 * color.B;

            return brightness < 123 ? DeepBrush : LightBrush;
        }

        public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture)
        {
            return Binding.DoNothing;
        }
    }
}
